package com.rtline.business.aop;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * <p>LoggingCostTimeAspect ：打印controller内所有方法的执行时间
 *
 * <p>change history:
 *
 * <pre>
 * date         defect       person          comments
 * --------------------------------------------------------------------------------
 * 2025/5/31    ********     Tao Ren    create file.
 * </pre>
 *
 * @author Tao Ren
 * @date 2025/5/31 18:19
 */
@Aspect
@Component
public class LoggingCostTimeAspect {
    private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);

    // 定义切入点，匹配com.rtline.business.controller包下的所有方法
    @Around("execution(* com.rtline.business.controller..*.*(..))")
    public Object logMethodExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis(); // 记录方法开始时间

        // 执行目标方法
        Object result = joinPoint.proceed();

        long endTime = System.currentTimeMillis(); // 记录方法结束时间
        long executionTime = endTime - startTime; // 计算方法执行时间

        // 获取方法信息
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String methodName = signature.getMethod().getName();
        String className = joinPoint.getTarget().getClass().getName();

        // 打印日志
        logger.info("Method: {}.{} executed in {}ms", className, methodName, executionTime);

        return result;
    }
}
